package server

import "bytes"

type Response interface {
	Write(content string)
	AddHead(header string, value string)
	SetContextType(value string)
	GetBody() string
	GetHeaders() []Header
	GetContentType() string
	ToHttpStr() string
	Code(code string)
	SetHeaders(headers []Header)
	GetCode() string
}


type MyResponse struct {
	headers []Header

	//body内容，可能是文字也可能是图片等资源
	body string

	contentType string

	code string
}

func (myResponse *MyResponse) Write(content string) {
	myResponse.body = content;
}

func (myResponse *MyResponse) Code(code string) {
	myResponse.code = code;
}

func (myResponse *MyResponse) AddHead(header string, value string) {
	headers := myResponse.headers
	newHeader := Header{Key: header, Value: value}
	nHeaders := append(headers, newHeader)
	myResponse.headers = nHeaders
}

func (myResponse *MyResponse) SetContextType(value string) {
	myResponse.contentType = value
}

func (myResponse *MyResponse) SetHeaders(headers []Header) {
	myResponse.headers = headers
}

func (myResponse *MyResponse) GetBody() string {
	return myResponse.body
}

func (myResponse *MyResponse) GetHeaders() []Header {
	return myResponse.headers
}

func (myResponse *MyResponse) GetContentType() string {
	return myResponse.contentType
}

func (myResponse *MyResponse) GetCode() string {
	return myResponse.code
}

func (myResponse *MyResponse) ToHttpStr() string {
	bufferString := bytes.NewBufferString("HTTP/1.1 ")
	bufferString.WriteString(myResponse.code + " ")
	bufferString.WriteString("ok\n")
	bufferString.WriteString("Content-Type: " + myResponse.GetContentType() + "\n")
	//处理header中的内容
	headers := myResponse.GetHeaders()
	for _, header := range headers {
		bufferString.WriteString(header.Key + ": " + header.Value + "\n")
	}
	//处理body
	bufferString.WriteString("\r\n" + myResponse.body)
	return bufferString.String()
}